﻿//*********************************************************************
//
//  文件名：BranchController
//
//  作者： Pwp
//
//  作用：机构管理模块
//
//  日期：2015-09-15
//
//*********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Application.WebAPI.Filter;
using YouTravel.DomainService;
using Framework.IOC;
using Framework.Common;
using Framework.Common.Paged;
using YouTravel.QueryModels;
using YouTravel.ViewModels;
using YouTravel.Framework.ResourceMessage;
using YouTravel.DomainModels;
using YouTravel.Framework.Enums;
using Framework.Common.Exceptions;

namespace Application.WebAPI.Controllers
{
	[RoutePrefix("api/special")]
    public class ContractController : BaseController
    {
		IContractService contractService;
        DataResult dataResult = new DataResult();
		public ContractController(IContractService contractService)
            : base()
        {
			this.contractService = contractService;
        }
        /// <summary>
        /// 专线列表
        /// </summary>
		/// <param name="inputSpecial"></param>
        /// <returns></returns>
		[Route("specialcontractlist")]
        [HttpPost]
		public DataResult GetContractList(PagedParam<SpecialContractQuery> inputSpecial)
        {
			#region 角色验证
			//分社访问
			if (LoginUser.Type != 0 && LoginUser.Type != UserType.Branch)
			{
				throw new DataOperationPermissions(BusinessResourceMessage.NoPower);
			}
			#endregion
			//获取分社ID
			if (LoginUser.Type == UserType.Branch)
			{
				inputSpecial.QueryDto.BranchId = (int)LoginUser.BranchId;
			}
            dataResult.Code = ResponseStatusCode.Success;
			dataResult.Msg = BusinessResourceMessage.Success;
			dataResult.Data = contractService.GetBranchList(inputSpecial);
            return dataResult;
        }

		/// <summary>
		/// 续约合约
		/// </summary>
		/// <param name="inputContract"></param>
		/// <returns></returns>
		[Route("renewalcontract")]
		[HttpPost]
		public DataResult RenewalContract(ContractViewModel inputContract)
		{
			#region 角色验证
			//分社访问
			if (LoginUser.Type != 0 && LoginUser.Type != UserType.Branch)
			{
				throw new DataOperationPermissions(BusinessResourceMessage.NoPower);
			}
			#endregion

			#region 输入验证
			if (string.IsNullOrEmpty(inputContract.ContractName))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemCanNotNull, "合同名称"));
			if (inputContract.ContractName.Length > 50)
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemLenError, "合同名称", "50"));
			if (!CommonValidator.isDateTime(inputContract.EndDate.ToString()))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemFormatError, "合同到期时间"));
			if (DateTime.Now > DateTime.Parse(inputContract.EndDate))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemComparison, "合同到期时间","当前时间"));
			if (inputContract.Attachments.Count < 1 || string.IsNullOrEmpty(inputContract.Attachments.FirstOrDefault().ToString()))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemCanNotNull, "合同附件"));
			bool isErrAttachments = false;
			bool isErrLenAttachments = false;
			foreach (var item in inputContract.Attachments)
			{
				string fileEnd = item.Item1.Trim().Substring(item.Item1.Trim().LastIndexOf(".") + 1).ToLower();
				if (fileEnd != "gif" && fileEnd != "jpg" && fileEnd != "png" && fileEnd != "jpeg" && fileEnd != "bmp" && fileEnd != "pdf")
				{
					isErrAttachments = true;
					break;
				}
				if (item.Item1.Length > 50)
				{
					isErrLenAttachments = true;
					break;
				}
			}
			if (isErrAttachments)
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemFormatError, "合同附件"));
			if (isErrLenAttachments)
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemLenError, "合同附件名称", "50"));
			#endregion

			inputContract.OperatorID = LoginUser.ID;
			inputContract.OperatorName = LoginUser.Name;
			inputContract.OptionTime = DateTime.Now;
			contractService.RenewalContract(inputContract);
			dataResult.Code = ResponseStatusCode.Success;
			dataResult.Msg = BusinessResourceMessage.Success;
			return dataResult;
		}

		/// <summary>
		/// 专线供应商/销售商列表
		/// </summary>
		/// <param name="inputSpecial"></param>
		/// <returns></returns>
		[Route("sellersupplierspecialcontractlist")]
		[HttpPost]
		public DataResult GetContractSellerSupplierList(PagedParam<SpecialContractQuery> inputSpecial)
		{
			#region 角色验证
			//分社权限
			if (LoginUser.Type != 0 && LoginUser.Type != UserType.Branch)
			{
				throw new DataOperationPermissions(BusinessResourceMessage.NoPower);
			}
			#endregion

			#region 输入验证
			//if (inputSpecial.QueryDto.SpecialId == 0)
			//	throw new DataOperationPermissions(string.Format(BusinessResourceMessage.ItemCanNotNull,"专线"));
			#endregion

			dataResult.Code = ResponseStatusCode.Success;
			dataResult.Msg = BusinessResourceMessage.Success;
			dataResult.Data = contractService.GetSellerSupplierList(inputSpecial);
			return dataResult;
		}

		/// <summary>
		/// 废弃合同
		/// </summary>
		/// <param name="inputSellerSupplier"></param>
		/// <returns></returns>
		[Route("abandonedcontract")]
		[HttpPost]
		public DataResult AbandonedContract(SellerSupplier inputSellerSupplier)
		{
			#region 角色验证
			//分社访问
			if (LoginUser.Type != 0 && LoginUser.Type != UserType.Branch)
			{
				throw new DataOperationPermissions(BusinessResourceMessage.NoPower);
			}
			#endregion

			#region 输入验证
			if (inputSellerSupplier.ID == 0)
				throw new DataValidationException(string.Format(BusinessResourceMessage.Inexistent, "合同"));
			#endregion

			inputSellerSupplier.UpdaterId = LoginUser.ID;
			inputSellerSupplier.UpdateTime = DateTime.Now;
			contractService.AbandonedContract(inputSellerSupplier);
			dataResult.Code = ResponseStatusCode.Success;
			dataResult.Msg = BusinessResourceMessage.Success;
			return dataResult;
		}

		/// <summary>
		/// 添加供应商/销售商合同
		/// </summary>
		/// <param name="inputcontract"></param>
		/// <returns></returns>
		[Route("addcontract")]
		[HttpPost]
		public DataResult AddContract(ContractViewModel inputContract)
		{
			#region 角色验证
			//分社访问
			if (LoginUser.Type != 0 && LoginUser.Type != UserType.Branch)
			{
				throw new DataOperationPermissions(BusinessResourceMessage.NoPower);
			}
			#endregion

			#region 输入验证

			string strNameType = "供应商";
			if (inputContract.Type == (int)SellerSupplierType.Seller)
				strNameType = "销售商";

			if (inputContract.SpecialId == 0)
				throw new DataValidationException(string.Format(BusinessResourceMessage.Inexistent, "专线"));
			if (string.IsNullOrEmpty(inputContract.Name))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemCanNotNull, strNameType+"名称"));
			if (inputContract.Name.Length > 50)
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemLenError, strNameType+"名称", "50"));
			if (string.IsNullOrEmpty(inputContract.Bank))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemCanNotNull, "开户行"));
			if (inputContract.Bank.Length > 30)
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemLenError, "开户行", "30"));
			if (string.IsNullOrEmpty(inputContract.ChargeBankNumber))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemCanNotNull, "银行帐号"));
			if (inputContract.ChargeBankNumber.Length > 20)
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemLenError, "银行帐号", "20"));
			if (string.IsNullOrEmpty(inputContract.ChargeName))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemCanNotNull, "负责人"));
			if (inputContract.ChargeName.Length > 20)
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemLenError, "负责人", "20"));
			if (string.IsNullOrEmpty(inputContract.CertificateNum))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemCanNotNull, "身份证"));
			if (inputContract.CertificateNum.Length > 18)
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemLenError, "身份证", "18"));
			if (!CommonValidator.isMobile(inputContract.Phone))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemFormatError, "手机"));
			if (string.IsNullOrEmpty(inputContract.ContractName))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemCanNotNull, "合同名称"));
			if (inputContract.ContractName.Length > 50)
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemLenError, "合同名称", "50"));
			if (!CommonValidator.isDateTime(inputContract.EndDate))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemFormatError, "合同到期时间"));
			if (inputContract.Attachments.Count < 1 || string.IsNullOrEmpty(inputContract.Attachments.FirstOrDefault().ToString()))
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemCanNotNull, "合同附件"));
			bool isErrAttachments = false;
			bool isErrLenAttachments = false;
			foreach (var item in inputContract.Attachments)
			{
				string fileEnd = item.Item1.Trim().Substring(item.Item1.Trim().LastIndexOf(".") + 1).ToLower();
				if (fileEnd != "gif" && fileEnd != "jpg" && fileEnd != "png" && fileEnd != "jpeg" && fileEnd != "bmp" && fileEnd != "pdf")
				{
					isErrAttachments = true;
					break;
				}
				if (item.Item1.Length > 50)
				{
					isErrLenAttachments = true;
					break;
				}
			}
			if (isErrAttachments)
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemFormatError, "合同附件"));
			if (isErrLenAttachments)
				throw new DataValidationException(string.Format(BusinessResourceMessage.ItemLenError, "合同附件名称", "50"));
			#endregion

			inputContract.OperatorID = LoginUser.ID;
			inputContract.OperatorName = LoginUser.Name;
			inputContract.OptionTime = DateTime.Now;
			contractService.AddContract(inputContract);
			dataResult.Code = ResponseStatusCode.Success;
			dataResult.Msg = BusinessResourceMessage.Success;
			return dataResult;
		}
    }
}